﻿#include "ndt_base_scene.h"

#include <QApplication>
#include <QGraphicsTextItem>
#include "ruler_manager.h"

namespace eintik::presentation::viewcore {

NdtScanScene::NdtScanScene(QObject *parent)
    : QGraphicsScene(parent)
{
    refreshDataTimer.setSingleShot(true);
    refreshDataTimer.setInterval(displayInterval); // 每秒最多刷新30帧的显示 15ms不是30帧，是66帧
    QObject::connect(this, &NdtScanScene::signalRefreshDataTimerStart, this,
                     &NdtScanScene::slotRefreshDataTimerStart, Qt::QueuedConnection);
    QObject::connect(&refreshDataTimer, &QTimer::timeout, this,
                     &NdtScanScene::slotRefreshDataTimeout);

    colorMap.resize(260);

    for (auto i = 0; i < 256; i++)
        colorMap[i] = QColor((qRgb(i, i, i)));

    if (scanNameItem == nullptr) {
        scanNameItem = new QGraphicsTextItem;
        scanNameItem->setZValue(4);
        scanNameItem->setData(0, "top-true");
    }

    this->addItem(scanNameItem);
    QFont f = scanNameItem->font();
    f.setPointSize(14);
    f.setBold(true);
    scanNameItem->setFont(f);
    scanNameItem->setFont(f);
    scanNameItem->setPlainText("");
    scanNameItem->setDefaultTextColor(Qt::white);
    scanNameItem->hide();
}

void NdtScanScene::setColorMap(const QVector<QColor> &colorVector)
{
    colorMap = colorVector;
    colorTable.resize(colorVector.size());
    std::transform(colorVector.begin(), colorVector.end(), colorTable.begin(),
                   [&](const QColor c) -> QRgb { return c.rgb(); });
}

VIEW_TYPE NdtScanScene::getViewType() const
{
    return Type;
}

void NdtScanScene::init()
{
    this->View->getRulerManager()->setColorMap(this->colorMap, 2);
}

void NdtScanScene::updateRulers()
{
    for (auto i = 0; i < 4; i++) {
        this->View->getRulerManager()->updateRuler(i);
    }
}

void NdtScanScene::slotRefreshDataTimerStart(bool)
{
    refreshDataTimer.start();
    // 如果窗口不可见，那么就不刷新
    if (sceneVisible())
        this->update();
}

void NdtScanScene::slotRefreshDataTimeout()
{
    refreshDataTimer.stop();
}

void NdtScanScene::setScanView(NdtScanView *view)
{
    View = view;
}

bool NdtScanScene::sceneVisible()
{
    // 获取View的父窗口部件（通常是包含View的窗口）
    QWidget *parentWidget = View->parentWidget();
    if (!parentWidget) {
        return false;
    }

    // 检查窗口本身是否被设置为可见状态
    if (!parentWidget->isVisible()) {
        return false;
    }

    // 检查窗口是否对顶级窗口可见
    if (!parentWidget->isVisibleTo(parentWidget->window())) {
        return false;
    }

    // 检查窗口是否未被最小化
    return parentWidget->windowState() != Qt::WindowMinimized;
}

void NdtScanScene::setRefreshDataTimerOn(bool f)
{
    if (!refreshDataTimer.isActive())
        emit signalRefreshDataTimerStart(f);
}

void NdtScanScene::updateScan(bool f)
{
    setRefreshDataTimerOn(f);
}

NdtScanScene::~NdtScanScene() { }

}
